package com.jtny.nytb.valid.validator;

import com.jtny.nytb.valid.annotation.ValueValid;
import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author 智慧能源中心 - 伍天宇
 * @package com.jtny.nytb.valid.validator
 * @fileName ValueValidator.java
 * @createTime 2023年09月15日 15:15
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
public class ValueValidator implements ConstraintValidator<ValueValid, Object> {

    private String[] strValues;
    private int[] intValues;
    private boolean ignoreEmpty;

    @Override
    public void initialize(ValueValid constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
        ignoreEmpty = constraintAnnotation.ignoreEmpty();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (ignoreEmpty && ObjectUtils.isEmpty(value)) {
            return true;
        }

        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (Integer s : intValues) {
                if (s == value) {
                    return true;
                }
            }
        }
        return false;
    }
}

